package org.chen.controller;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.chen.model.sys.ImageResource;
import org.chen.response.Page;
import org.chen.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/images")
@Slf4j
public class ImageResourceController {
    
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AsyncTaskExecutor taskExecutor; // 用于异步处理
    
    @GetMapping
    public Result<Page<ImageResource>> getImageList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String type) {
        
        Query query = new Query();
        if (StringUtils.hasText(type)) {
            query.addCriteria(Criteria.where("type").is(type));
        }
        query.addCriteria(Criteria.where("isDeleted").is(false));
        
        long total = mongoTemplate.count(query, ImageResource.class);
        
        query.skip((long) (page - 1) * size).limit(size);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        
        List<ImageResource> records = mongoTemplate.find(query, ImageResource.class);

        records.forEach(record -> {
            record.setPath("");
        });

        return Result.success(new Page<>(records, total));
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> deleteImage(@PathVariable String id) {
        Update update = new Update().set("isDeleted", true);
        mongoTemplate.updateFirst(
            Query.query(Criteria.where("id").is(id)),
            update,
            ImageResource.class
        );
        return Result.success();
    }

    @DeleteMapping("/batch")
    public Result<Void> batchDeleteImages(@RequestBody List<String> ids) {
        try {
            for (String id : ids) {
                ImageResource image = mongoTemplate.findById(id, ImageResource.class);
                if (image != null) {
                    // 删除物理文件
                    File file = new File(image.getPath());
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }

            // 批量删除数据库记录
            mongoTemplate.remove(Query.query(Criteria.where("id").in(ids)), ImageResource.class);

            return Result.success();
        } catch (Exception e) {
            log.error("Batch delete images failed", e);
            throw new RuntimeException("Batch delete images failed", e);
        }
    }

    @DeleteMapping("/clear-all")
    public Result<Void> clearAllImages() {
        try {
            // 1. 先获取所有未删除的图片记录
            Query query = Query.query(Criteria.where("isDeleted").is(false));
            List<ImageResource> allImages = mongoTemplate.find(query, ImageResource.class);

            if (allImages.isEmpty()) {
                return Result.success();
            }

            // 2. 启动异步任务处理文件删除
            taskExecutor.execute(() -> {
                try {
                    log.info("Starting batch deletion of {} images", allImages.size());
                    int totalImages = allImages.size();
                    int processedImages = 0;
                    int batchSize = 100;
                    List<List<ImageResource>> batches = Lists.partition(allImages, batchSize);

                    for (List<ImageResource> batch : batches) {
                        processBatch(batch);
                        processedImages += batch.size();
                        log.info("Processed {}/{} images", processedImages, totalImages);
                    }

                    log.info("Completed deletion of all images");
                } catch (Exception e) {
                    log.error("Error during batch image deletion", e);
                }
            });

            return Result.success();
        } catch (Exception e) {
            log.error("Clear all images failed", e);
            throw new RuntimeException("Clear all images failed", e);
        }
    }

    private void processBatch(List<ImageResource> batch) {
        try {
            // 1. 批量更新数据库记录
            List<String> batchIds = batch.stream()
                    .map(ImageResource::getId)
                    .collect(Collectors.toList());

            Update update = new Update()
                    .set("isDeleted", true)
                    .set("updateTime", new Date());

            mongoTemplate.updateMulti(
                    Query.query(Criteria.where("id").in(batchIds)),
                    update,
                    ImageResource.class
            );

        } catch (Exception e) {
            log.error("Error processing batch", e);
            throw new RuntimeException("Batch processing failed", e);
        }
    }
}